package com.saas.ability.gateway.filter;

import com.saas.ability.core.base.constant.retcode.RetCode;
import com.saas.ability.core.base.exception.AuthenticateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.netflix.zuul.context.RequestContext;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 鉴权验证
 *
 */
@Component
public class AuthTokenFilter extends AbstractFilter {


//    @Autowired
//    AdminCacheService adminCacheService;
//todo 权限相关service
	@Override
	public String filterType() {
		return "pre";
	}

	@Override
	public boolean shouldFilter() {
		RequestContext ctx = RequestContext.getCurrentContext();
		String uri = ctx.getRequest().getRequestURI();
		if(isVerifyToken(uri)){
			return true;
		}else if(isWhitePath(uri)){
			return false;
		}
		return false;
	}

	/**
	 * 需要验证登录token的请求
	 * @param requestURI
	 * @return
	 */
	private boolean isVerifyToken(String requestURI){
		if (requestURI.contains("/saas-oauth/")){
			return true;
		}
		return false;
	}

	/**
	 * 是否白名单地址
	 * @param requestUri
	 * @return
	 */
	public boolean isWhitePath(String requestUri){
		return true;
	}

	@Override
	public Object run() {
//		System.out.println("==============执行路由前=================");
		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest request = ctx.getRequest();
		String accessToken = request.getHeader("accessToken");
		if(!StringUtils.isEmpty(accessToken)){
//			AdminCache adminCache = adminCacheService.getLoginUserInfo(accessToken);
//			if(adminCache == null){
//				String uri = request.getRequestURI();
//				logger.info("请求接口[{}]没有获取用户登录信息,accessToken:{}",uri,accessToken);
//				throw new AuthenticateException(RetCode.AUTH_INVALID.retCode, "用户不存在，不允许操作接口");
//			}else{
//				ThreadLocalAdmin.setAdminCache(adminCache);
//			}
			//todo 权限相关判断+传递
		}else {
			logger.error("用户没有登录，不允许操作接口");
			throw new AuthenticateException(RetCode.AUTH_INVALID.retCode, "用户没有登录，不允许操作接口");
		}
		ctx.setSendZuulResponse(true);
		ctx.setResponseStatusCode(200);
		return null;
	}
	
	@Override
	public int filterOrder() {
		return Integer.MIN_VALUE + 2;
	}

}
